package com.service.impl;

import com.dao.BookDao;
import com.dao.OrderDao;
import com.dao.OrderItemDao;
import com.dao.impl.BookDaoImpl;
import com.dao.impl.OrderDaoImpl;
import com.dao.impl.OrderItemDaoImpl;
import com.pojo.*;
import com.service.OrderService;


import java.util.Date;
import java.util.List;
import java.util.Map;

public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private BookDao bookDao = new BookDaoImpl();
    @Override
    public String createOrder(Cart cart, Integer userId) {

        //注意：先有订单，再有订单项，否则订单号保存不进去
        //订单号===“唯一” 可以使用时间戳
        String orderId = System.currentTimeMillis()+""+userId;//时间戳和用户id相加，保证商品编号的唯一性
        //创建一个订单对象
        Order order = new Order(orderId, new Date(),cart.getTotalPrice(),0,userId);
        //保存订单
        orderDao.saveOrder(order);

//        int i=12/0;

        //遍历购物车中每一个商品项，转化成为订单项保存到数据库
        for (Map.Entry<Integer, CartItem>entry : cart.getItems().entrySet()) {
            //获取每一个购物车中的商品项
            CartItem cartItem = entry.getValue();
            //转化成为每一个订单项
            OrderItem orderItem = new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(),orderId);
            //保存订单项到数据库
            orderItemDao.saveOrderItem(orderItem);

            //更新库存和销量
            Book book = bookDao.queryBookById(cartItem.getId());
            book.setSales(book.getSales()+cartItem.getCount());
            book.setStock(book.getStock()-cartItem.getCount());
            bookDao.updateBook(book);
        }
        cart.clear();//结账后清空购物车
        return orderId;
    }

    @Override
    public List<Order> showMyOrders(Integer userid) {
        return orderDao.queryMyOrders(userid);
    }

    @Override
    public List<OrderItem> showOrderItem(String orderId) {
        return orderItemDao.queryForOrderItems(orderId);
    }


}
